package com.ke.searchhouse.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import com.ke.searchhouse.base.Response;
import com.ke.searchhouse.config.AliCloudConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @author  keke
 * @create  2018/10/12 0012 下午 8:50
 * @desc  文件上传到阿里云服务接口
 **/
@Service
@Slf4j
public class TenantCloudUploadService {
    private static final Integer UPLOAD_ERROR_STATUS = 5501;


    public Response upload(MultipartFile file) {
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(AliCloudConfig.ENDPOINT,
                AliCloudConfig.ACCESS_KEY_ID, AliCloudConfig.ACCESS_KEY_SECRET);

        try {
            ossClient.putObject(AliCloudConfig.FILE_BUCKET_NAME, file.getOriginalFilename(), file.getInputStream());
        } catch (IOException e) {
            log.error("上传文件出错: {}", e.getMessage());
            return Response.ofMessage(UPLOAD_ERROR_STATUS, e.getMessage());
        }

        // 关闭OSSClient。
        ossClient.shutdown();

        return Response.ofSuccess(file.getOriginalFilename());
    }


}
